<template>
  <div class="table-container pull-chheight">
    <avue-crud :option="tableOption" v-model="user" :data="tableData" :table-loading="tableLoading"
               :page="listQuery" ref="crud" @row-save="handleSave"
               @row-update="handleUpdate"  @size-change="handleSizeChange"
               @refresh-change="handlerefreshChange" @current-change="handleCurrentChange"
               @search-change="handleSearchChange" @selection-change="handleSelectionChange">
      <template slot="menuRight">
        <el-button v-if="permissions.sales_intention_entry_add" title="新增" type="primary" icon="el-icon-plus" @click="handleAdd" circle size="small"></el-button>
        <el-button v-if="permissions.sales_intention_entry_upd" title="修改" type="primary" icon="el-icon-edit" @click="handleRowEdit" circle size="small"></el-button>
      </template>

      <template slot-scope="scope" slot="collectUser">
        <el-tag>{{ userIdToName(scope.row.collectUser) }}</el-tag>
      </template>

      <template slot-scope="scope" slot="collectUserForm">
        <!--<el-input>{{ userIdToName(scope.row.collectUser) }}</el-input>-->

        <el-cascader :options="users" v-model="defaultUser"></el-cascader>
        <input type="hidden" v-model="user.collectUser"/>
      </template>

      <template slot-scope="props" slot="expand">
        <el-form label-position="left" inline class="demo-table-expand">
          <el-form-item label="姓名">
            <span>{{ props.row.fname }}</span>
          </el-form-item>
          <el-form-item label="手机号1">
            <span>{{ props.row.tel1 }}</span>
          </el-form-item>
          <el-form-item label="手机号2">
            <span>{{ props.row.tel2 }}</span>
          </el-form-item>
          <el-form-item label="意向等级">
            <span>{{ setDicData(props.row.intentionLevel) }}</span>
          </el-form-item>
          <el-form-item label="意向校区">
            <span>{{ setDicData(props.row.school) }}</span>
          </el-form-item>
          <el-form-item label="学员状态">
            <span>{{ setDicData(props.row.bizStatus) }}</span>
          </el-form-item>
          <el-form-item label="收集人">
            <span>{{ userIdToName(props.row.collectUser) }}</span>
          </el-form-item>
          <el-form-item label="创建时间">
            <span>{{ formatDate(props.row.createTime) }}</span>
          </el-form-item>
        </el-form>
      </template>
    </avue-crud>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {
    intentionEntryPage,
    putObj,
    delObj,
    checkInformation
  } from '@/api/training/training_student'
  import tabOption from '@/const/sales/sales_intention_entry'
  import { addObj } from '@/api/sales/sales_intention_entry'
  import {getListByStudent} from '@/api/sales/sales_intention_flowup'
  import {validatenull} from '@/util/validate'
  import {formatDateS, findParent2} from '@/util/util.js'
  import {getUserDeptPath, getDeptUserTree} from '@/api/user'
  import {initDicList} from '@/api/dict'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  export default {
    name: 'sales_intention_entry',
    directives: {
      waves
    },
    data() {
      return {
        tableSearch: {},
        tableOption: tabOption, // 表格设置属性
        tableData: [], // 表格的数据
        tableRow: {},
        // tablePage: 1,
        tableLoading: false,
        tabelObj: {},
        user: {},
        users: [],
        defaultUser: [],
        listQuery: {
          total: 0, //  总页数
          currentPage: 1, //  当前页数
          pageSize: 10 //  每页显示多少条
        },
        totalPage: null,
        // callListQuery: {
        //   page: 1,
        //   limit: 10
        // },
        callRecordTableData: [],
        total: null,
        dictMap: []
      }
    },
    beforeCreate() {
    },
    created() {
      this.handleList()
      this.getDicList()
      this.initUserDic()
    },
    watch: {},
    mounted() {
    },
    computed: {
      ...mapGetters(['permissions', 'menuAll'])
    },
    props: [],
    methods: {
      initUserDic() {
        getDeptUserTree().then(response => {
          this.users = response.data
        })
      },
      userIdToName(userId) {
        return findParent2(this.users, userId)
      },
      formatDate(date) {
        if (date != null) {
          return formatDateS(new Date(date), 'yyyy-MM-dd hh:mm:ss')
        } else {
          return '-'
        }
      },
      setDicData(value) {
        for (let i = 0; i < this.dictMap.length; i++) {
          for (var key in this.dictMap[i]) {
            if (key === value) {
              return this.dictMap[i][key]
            }
          }
        }
      },
      getDicList() {
        initDicList().then(response => {
          this.dictMap = response.data
        })
      },
      /**
       * 获取用户组织路径
       * @param userId 用户ID
       */
      getUserDeptPath(userId) {
        getUserDeptPath(userId).then(response => {
          this.defaultUser = response.data
        })
      },
      /**
       * @title 刷新数据
       *
       **/
      handlerefreshChange(page) {
        this.handleList(this.tableSearch)
        this.$notify({
          message: `刷新数据成功`,
          type: 'success'
        })
      },
      /**
       * @title 权限更新
       *
       **/
      handleGradeUpdate() {
        this.tabelObj.check = [].concat(this.grade.check)
        this.tabelObj = {}
        this.grade.check = []
        this.grade.box = false
      },
      /**
       * @title 权限选择
       *
       **/
      handleGradeCheckChange(data, checked, indeterminate) {
        if (checked) {
          this.grade.check.push(data.id)
        } else {
          this.grade.check.splice(this.grade.check.indexOf(data.id), 1)
        }
      },
      handleRowEdit() {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要编辑的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        this.handleEdit(this.tableRow[0], -1)
      },
      handleEdit(row, index) {
        this.$refs.crud.rowEdit(row, index)
        if (!validatenull(row.followUpUser)) {
          this.getUserDeptPath(row.followUpUser)
        }
      },
      /**
       * @title 打开权限
       */
      handleGrade(row, index) {
        this.$store.dispatch('GetMenuAll').then(data => {
          this.grade.box = true
          this.tabelObj = row
          this.grade.check = this.tabelObj.check
        })
      },
      /**
       * @title 导出excel
       *
       **/
      handleExport() {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['username', 'name']
          const filterVal = ['username', 'name']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel(tHeader, data, this.filename)
        })
      },
      /**
       * @title 页面改变值
       *
       **/
      handleCurrentChange(val) {
        this.listQuery.currentPage = val
        this.handleList()
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.handleList()
      },
      /**
       * @title 搜索按钮回掉
       *
       **/
      handleSearchChange(form) {
        this.tableSearch = form
        this.tableLoading = true
        var params = Object.assign({}, form)
        params.page = this.listQuery.currentPage
        params.limit = this.listQuery.pageSize
        intentionEntryPage(params).then(response => {
          this.tableData = response.data.records
          this.listQuery = {
            total: response.data.total
          }
          this.tableLoading = false
        })
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd() {
        this.$refs.crud.rowAdd()
      },
      /**
       * @title 选中第几行
       * @param row 选中那几行数据
       * @detail 调用crud的toggleSelection方法即可
       *
       **/
      toggleSelection(row) {
        this.$refs.crud.toggleSelection(row)
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        this.tableLoading = true
        intentionEntryPage({
          page: this.listQuery.currentPage,
          limit: this.listQuery.pageSize
        }).then(response => {
          this.tableData = response.data.records
          this.formatList()
          this.listQuery = {
            total: response.data.total,
            currentPage: response.data.current,
            pageSize: response.data.size
          }
          this.callListQuery = {
            page: response.data.current,
            limit: response.data.size
          }
          this.tableLoading = false
        })
      },
      formatList() {
        for (var i = 0; i < this.tableData.length; i++) {
          this.tableData.bizStatus = this.setDicData(this.tableData[i].bizStatus)
        }
      },
      /**
       * @title 当前选中的数据
       * @param val 选中的值
       *
       **/
      handleSelectionChange(val) {
        this.tableRow = val
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave(row, done) {
        done()
        checkInformation(row.tel1).then(response => {
          if (!response.data.data) {
            this.$notify({
              title: '提示',
              message: '手机号1已存在 ！',
              type: 'warning',
              duration: 2000
            })
            return
          }
          checkInformation(row.tel2).then(response => {
            if (row.tel2.trim() !== '') {
              if (!response.data.data) {
                this.$notify({
                  title: '提示',
                  message: '手机号2已存在 ！',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
            }
            row.bizStatus = '2201'
            addObj(Object.assign({}, row)).then(() => {
              this.dialogFormVisible = false
              this.handleList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          })
        })
      },
      /**
       * @title 行双击
       * @param row 为当前的数据
       * @param event 事件
       *
       **/
      // handleRowDBLClick(row, event) {
      //   this.$notify({
      //     showClose: true,
      //     message: '双击',
      //     type: 'success'
      //   })
      // },

      /**
       * @title 行单机
       * @param row 为当前的数据
       * @param event 事件
       * @param column 列
       *
       **/
      // handleRowClick(row, event, column) {
      //   this.$notify({
      //     showClose: true,
      //     message: '单机',
      //     type: 'success'
      //   })
      // },
      handleRowDel() {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要删除的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        this.handleDel(this.tableRow[0], -1)
      },
      /**
       * @title 数据删除
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       *
       **/
      handleDel(row, index) {
        this.$confirm(`是否确认删除序号为${row.name}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(row).then(response => {
            this.dialogFormVisible = false
            this.handleList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done) {
        checkInformation(row.tel1).then(response => {
          if (!response.data.data && (response.data.msg - 0) !== row.fid) {
            this.$notify({
              title: '提示',
              message: '手机号1已存在 ！',
              type: 'warning',
              duration: 2000
            })
            return
          }
          checkInformation(row.tel2).then(response => {
            if (!response.data.data && (response.data.msg - 0) !== row.fid) {
              this.$notify({
                title: '提示',
                message: '手机号1已存在 ！',
                type: 'warning',
                duration: 2000
              })
              return
            }
            putObj(row).then(data => {
              this.handleList()
              this.tableData.splice(index, 1, Object.assign({}, row))
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
              done()
            })
          })
        })
      },
      /**
       * @title 表单关闭前处理
       * @param done
       *
       **/
      // boxhandleClose(done) {
      //   this.defaultUser = []
      //   this.$notify({
      //     showClose: true,
      //     message: '表单关闭前处理事件',
      //     type: 'success'
      //   })
      //   done()
      // },
      // boxhandleOpen(show) {
      //   this.$notify({
      //     showClose: true,
      //     message: '表单打开前处理事件',
      //     type: 'success'
      //   })
      //   show()
      // },
      handleCallSizeChange(val) {
        this.callListQuery.limit = val
        this.getCallList()
      },
      handleCallCurrentChange(val) {
        this.callListQuery.page = val
        this.getCallList()
      },
      handleCalls() {
        this.getCallList(this.tableRow[0])
      },
      getCallList(row) {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要查看的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }

        this.grade.box = true
        getListByStudent(row.fid).then(data => {
          this.callRecordTableData = data.data.records
          this.total = data.data.length
          this.tableLoading = false
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .table-container {
    padding: 8px 10px;
  }

  .table-header {
    margin-bottom: 10px;
    & > .el-button {
      padding: 12px 25px;
    }
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
